"""
打板监控页面

提供完整的打板监控功能，包括：
- 实时涨停板监控
- 打板选股器
- 历史回测
- 市场情绪分析
- 龙头股识别

作者: AI Assistant
版本: 1.0.0
日期: 2024-10-10
"""

import streamlit as st
import pandas as pd
from datetime import datetime, timedelta
import plotly.graph_objects as go
import plotly.express as px
from typing import Optional

from core.limit_up_data import LimitUpDataFetcher, LimitUpHistory
from utils.market_sentiment import MarketSentiment
from utils.leader_detector import LeaderDetector


def limit_up_monitoring_page():
    """打板监控主页面"""
    
    st.markdown("# 📍 打板监控系统")
    st.markdown("实时监控涨停板，智能识别龙头股，把握短线机会")
    
    # 风险提示
    with st.expander("⚠️ 重要风险提示", expanded=False):
        st.warning("""
        **打板策略风险极高，请务必注意：**
        
        1. 💀 **高风险警告**
           - 次日低开风险极大，可能-10%
           - 情绪退潮时亏损迅速
           - 不适合大资金和新手
           
        2. 📊 **数据仅供参考**
           - 本系统仅供学习研究
           - 不构成任何投资建议
           - 投资有风险，入市需谨慎
           
        3. ✅ **建议先模拟**
           - 建议先用模拟盘验证
           - 充分了解策略风险
           - 严格执行纪律
        """)
    
    # 标签页
    tab1, tab2, tab3, tab4 = st.tabs([
        "📊 实时监控",
        "🎯 选股器", 
        "📈 历史回测",
        "🔥 市场情绪"
    ])
    
    with tab1:
        show_real_time_monitoring()
    
    with tab2:
        show_stock_selector()
    
    with tab3:
        show_historical_backtest()
    
    with tab4:
        show_market_sentiment()


def show_real_time_monitoring():
    """实时涨停板监控"""
    st.markdown("### 📊 今日涨停板实时监控")
    
    # 刷新按钮
    col1, col2, col3 = st.columns([1, 1, 4])
    with col1:
        if st.button("🔄 刷新数据", key="refresh_limit_up"):
            st.rerun()
    with col2:
        auto_refresh = st.checkbox("自动刷新", value=False)
    
    if auto_refresh:
        st.info("💡 自动刷新已开启，每30秒更新一次")
    
    # 获取今日涨停数据
    with st.spinner("正在获取今日涨停数据..."):
        limit_up_df = LimitUpDataFetcher.get_today_limit_up_pool()
    
    if limit_up_df is None:
        st.error("❌ 获取涨停数据失败，请检查网络连接")
        return
    
    if limit_up_df.empty:
        st.warning("⚠️ 今日暂无涨停股票")
        return
    
    # 显示概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("涨停家数", f"{len(limit_up_df)}只")
    
    with col2:
        if 'consecutive_limit_up' in limit_up_df.columns:
            max_consecutive = int(limit_up_df['consecutive_limit_up'].max())
            st.metric("最高连板", f"{max_consecutive}板")
        else:
            st.metric("最高连板", "N/A")
    
    with col3:
        # 计算早盘板占比
        early_count = 0
        if 'first_limit_up_time' in limit_up_df.columns:
            for time_str in limit_up_df['first_limit_up_time']:
                if pd.notna(time_str):
                    try:
                        parts = str(time_str).split(':')
                        if len(parts) >= 2:
                            hour, minute = int(parts[0]), int(parts[1])
                            if hour * 60 + minute < 600:
                                early_count += 1
                    except:
                        pass
        early_ratio = (early_count / len(limit_up_df) * 100) if len(limit_up_df) > 0 else 0
        st.metric("早盘板占比", f"{early_ratio:.1f}%")
    
    with col4:
        # 平均换手率
        if 'turnover_rate' in limit_up_df.columns:
            avg_turnover = limit_up_df['turnover_rate'].mean()
            st.metric("平均换手", f"{avg_turnover:.1f}%")
        else:
            st.metric("平均换手", "N/A")
    
    st.markdown("---")
    
    # 龙头股识别
    st.markdown("### 👑 市场龙头识别")
    leaders = LeaderDetector.detect_market_leader(limit_up_df, top_n=5)
    
    if not leaders.empty:
        # 显示龙头股
        display_cols = ['龙头排名', 'name', 'code', 'consecutive_limit_up', 
                       'first_limit_up_time', 'turnover_rate', 'leader_score']
        
        display_names = {
            '龙头排名': '排名',
            'name': '名称',
            'code': '代码',
            'consecutive_limit_up': '连板数',
            'first_limit_up_time': '首次涨停',
            'turnover_rate': '换手率(%)',
            'leader_score': '龙头得分'
        }
        
        available_cols = [col for col in display_cols if col in leaders.columns]
        leaders_display = leaders[available_cols].copy()
        leaders_display.rename(columns=display_names, inplace=True)
        
        st.dataframe(leaders_display, use_container_width=True, hide_index=True)
        
        # 龙头特征分析
        leader_char = LeaderDetector.analyze_leader_characteristic(leaders)
        if leader_char:
            with st.expander(f"🎯 龙头{leader_char.get('name', '')}详细分析"):
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.metric("连板数", f"{leader_char.get('consecutive', 0)}板")
                with col2:
                    st.metric("封板强度", f"{leader_char.get('seal_strength', 0):.2f}%")
                with col3:
                    st.metric("龙头得分", f"{leader_char.get('score', 0):.0f}分")
                
                st.markdown("**特征评价：**")
                for evaluation in leader_char.get('evaluations', []):
                    st.markdown(f"- {evaluation}")
                
                # 操作建议
                advice = LeaderDetector.get_follow_advice(leader_char)
                st.markdown(advice)
    else:
        st.info("暂无明显龙头股")
    
    st.markdown("---")
    
    # 完整涨停列表
    st.markdown("### 📋 完整涨停列表")
    
    # 筛选选项
    col1, col2, col3 = st.columns(3)
    with col1:
        filter_consecutive = st.selectbox(
            "连板数筛选",
            ["全部", "首板", "2连板", "3连板及以上"]
        )
    
    with col2:
        filter_time = st.selectbox(
            "涨停时间筛选",
            ["全部", "早盘板", "午盘板", "尾盘板"]
        )
    
    with col3:
        if 'industry' in limit_up_df.columns:
            industries = ["全部"] + list(limit_up_df['industry'].unique())
            filter_industry = st.selectbox("板块筛选", industries)
        else:
            filter_industry = "全部"
    
    # 应用筛选
    filtered_df = limit_up_df.copy()
    
    if filter_consecutive != "全部" and 'consecutive_limit_up' in filtered_df.columns:
        if filter_consecutive == "首板":
            filtered_df = filtered_df[filtered_df['consecutive_limit_up'] == 0]
        elif filter_consecutive == "2连板":
            filtered_df = filtered_df[filtered_df['consecutive_limit_up'] == 2]
        elif filter_consecutive == "3连板及以上":
            filtered_df = filtered_df[filtered_df['consecutive_limit_up'] >= 3]
    
    if filter_time != "全部" and 'first_limit_up_time' in filtered_df.columns:
        def get_time_category(time_str):
            try:
                parts = str(time_str).split(':')
                if len(parts) >= 2:
                    total_minutes = int(parts[0]) * 60 + int(parts[1])
                    if total_minutes < 600:
                        return "早盘板"
                    elif total_minutes < 810:
                        return "午盘板"
                    else:
                        return "尾盘板"
            except:
                pass
            return "未知"
        
        filtered_df = filtered_df[filtered_df['first_limit_up_time'].apply(get_time_category) == filter_time]
    
    if filter_industry != "全部" and 'industry' in filtered_df.columns:
        filtered_df = filtered_df[filtered_df['industry'] == filter_industry]
    
    st.info(f"🔍 筛选结果：{len(filtered_df)}只股票")
    
    # 显示列表
    if not filtered_df.empty:
        display_columns = ['name', 'code', 'price', 'change_pct', 'consecutive_limit_up',
                          'first_limit_up_time', 'turnover_rate', 'amount']
        
        available_display_cols = [col for col in display_columns if col in filtered_df.columns]
        
        st.dataframe(
            filtered_df[available_display_cols],
            use_container_width=True,
            hide_index=True,
            height=400
        )
    else:
        st.warning("没有符合筛选条件的股票")


def show_stock_selector():
    """打板选股器"""
    st.markdown("### 🎯 智能选股器")
    st.markdown("根据您的条件筛选最优打板标的")
    
    # 选股条件设置
    with st.expander("⚙️ 选股条件设置", expanded=True):
        col1, col2 = st.columns(2)
        
        with col1:
            min_consecutive = st.number_input(
                "最少连板数",
                min_value=0,
                max_value=10,
                value=0,
                help="0表示首板"
            )
            
            min_seal_strength = st.slider(
                "最小封板强度(%)",
                min_value=0.0,
                max_value=10.0,
                value=2.0,
                step=0.5
            )
        
        with col2:
            max_limit_time = st.time_input(
                "最晚涨停时间",
                value=pd.to_datetime("10:00").time()
            )
            
            min_turnover = st.slider(
                "最小换手率(%)",
                min_value=0.0,
                max_value=30.0,
                value=5.0,
                step=1.0
            )
    
    if st.button("🚀 开始选股", type="primary", use_container_width=True):
        with st.spinner("正在智能选股..."):
            limit_up_df = LimitUpDataFetcher.get_today_limit_up_pool()
        
        if limit_up_df is None or limit_up_df.empty:
            st.error("暂无涨停数据")
            return
        
        # 应用筛选条件
        filtered = limit_up_df.copy()
        
        # 连板数筛选
        if 'consecutive_limit_up' in filtered.columns:
            filtered = filtered[filtered['consecutive_limit_up'] >= min_consecutive]
        
        # 封板强度筛选
        if 'seal_amount' in filtered.columns and 'market_cap' in filtered.columns:
            filtered['seal_strength'] = (filtered['seal_amount'] / filtered['market_cap']) * 100
            filtered = filtered[filtered['seal_strength'] >= min_seal_strength]
        
        # 涨停时间筛选
        if 'first_limit_up_time' in filtered.columns:
            max_time_minutes = max_limit_time.hour * 60 + max_limit_time.minute
            def filter_time(time_str):
                try:
                    parts = str(time_str).split(':')
                    if len(parts) >= 2:
                        return int(parts[0]) * 60 + int(parts[1]) <= max_time_minutes
                except:
                    pass
                return False
            filtered = filtered[filtered['first_limit_up_time'].apply(filter_time)]
        
        # 换手率筛选
        if 'turnover_rate' in filtered.columns:
            filtered = filtered[filtered['turnover_rate'] >= min_turnover]
        
        # 显示结果
        st.success(f"✅ 选股完成！找到 {len(filtered)} 只符合条件的股票")
        
        if not filtered.empty:
            # 计算综合评分
            filtered['综合得分'] = 0.0
            
            for idx, row in filtered.iterrows():
                score = 0
                # 连板数得分
                consecutive = int(row.get('consecutive_limit_up', 0))
                score += min(consecutive * 15, 40)
                
                # 封板强度得分
                if 'seal_strength' in row:
                    seal = float(row['seal_strength'])
                    score += min(seal * 4, 30)
                
                # 涨停时间得分
                if 'first_limit_up_time' in row:
                    try:
                        parts = str(row['first_limit_up_time']).split(':')
                        if len(parts) >= 2:
                            minutes = int(parts[0]) * 60 + int(parts[1])
                            if minutes < 570:
                                score += 30
                            elif minutes < 600:
                                score += 20
                            else:
                                score += 10
                    except:
                        pass
                
                filtered.at[idx, '综合得分'] = min(score, 100)
            
            # 排序
            filtered = filtered.sort_values('综合得分', ascending=False)
            
            # 显示
            display_cols = ['name', 'code', 'consecutive_limit_up', 'first_limit_up_time',
                           'turnover_rate', '综合得分']
            available_cols = [col for col in display_cols if col in filtered.columns]
            
            st.dataframe(
                filtered[available_cols].head(20),
                use_container_width=True,
                hide_index=True
            )
        else:
            st.warning("没有符合条件的股票，请放宽筛选条件")


def show_historical_backtest():
    """历史打板回测"""
    st.markdown("### 📈 打板策略历史回测")
    st.markdown("验证打板策略的历史表现")
    
    st.info("🚧 功能开发中... 敬请期待！")
    
    # TODO: 实现历史回测功能
    st.markdown("""
    **即将推出：**
    - 首板次日收益统计
    - 连板接力成功率
    - 不同时间段涨停的次日表现
    - 不同板块的打板效果对比
    """)


def show_market_sentiment():
    """市场情绪分析"""
    st.markdown("### 🔥 市场情绪温度计")
    
    # 获取今日涨停数据
    with st.spinner("正在分析市场情绪..."):
        limit_up_df = LimitUpDataFetcher.get_today_limit_up_pool()
    
    if limit_up_df is None or limit_up_df.empty:
        st.warning("暂无数据，无法分析市场情绪")
        return
    
    # 情绪分析
    sentiment = MarketSentiment.analyze_sentiment(limit_up_df)
    
    # 显示情绪仪表盘
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric(
            "情绪分数",
            f"{sentiment['sentiment_score']}分",
            help="0-100分，分数越高市场越活跃"
        )
    
    with col2:
        st.metric(
            "情绪等级",
            sentiment['sentiment_level'],
            help="情绪热度分级"
        )
    
    with col3:
        st.metric(
            "市场状态",
            sentiment['market_status'],
            help="当前市场运行状态"
        )
    
    with col4:
        st.metric(
            "涨停家数",
            f"{sentiment['total_limit_up']}只",
            help="今日涨停股票总数"
        )
    
    # 情绪进度条
    st.markdown("#### 情绪温度条")
    progress_color = (
        "🟢" if sentiment['sentiment_score'] >= 60 else
        "🟡" if sentiment['sentiment_score'] >= 40 else
        "🔴"
    )
    st.progress(sentiment['sentiment_score'] / 100)
    st.caption(f"{progress_color} 当前情绪分数：{sentiment['sentiment_score']}/100")
    
    st.markdown("---")
    
    # 详细指标
    st.markdown("#### 📊 详细指标")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.metric("最高连板", f"{sentiment['max_consecutive']}板")
        st.metric("平均封板强度", f"{sentiment['avg_seal_strength']}%")
    
    with col2:
        st.metric("早盘板占比", f"{sentiment['early_board_ratio']}%")
        st.metric("强势板占比", f"{sentiment['strong_board_ratio']}%")
    
    with col3:
        st.info(f"📅 分析时间  \n{sentiment['analysis_time']}")
    
    st.markdown("---")
    
    # 板块分布
    st.markdown("#### 🏭 热门板块分布")
    industry_dist = MarketSentiment.get_industry_distribution(limit_up_df)
    
    if not industry_dist.empty:
        fig = px.bar(
            industry_dist.head(10),
            x='行业',
            y='涨停数',
            text='涨停数',
            title="涨停板块TOP10",
            color='涨停数',
            color_continuous_scale='Greens'
        )
        fig.update_traces(textposition='outside')
        fig.update_layout(height=400)
        st.plotly_chart(fig, use_container_width=True)
    else:
        st.info("暂无板块数据")
    
    st.markdown("---")
    
    # 操作建议
    st.markdown("#### 💡 操作建议")
    advice = MarketSentiment.get_sentiment_advice(sentiment)
    st.markdown(advice)

